package me.yuzho.study.concurrency;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static net.mindview.util.Print.*;


// Performs some portion of a task: 模拟一个任务的单个组成部分
class TaskPortion implements Runnable {
    private static int counter = 0;
    private final int id = counter++;
    private static Random rand = new Random(47);
    
    private final CountDownLatch latch;
    
    public TaskPortion(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public String toString() {
        return String.format("%1$-3d", id);
    }

    public void doWork() throws InterruptedException {
        TimeUnit.MICROSECONDS.sleep(rand.nextInt(2000));
        print(this + " completed");
    }

    @Override
    public void run() {
        
        try {
            doWork();
            latch.countDown();
        } catch (InterruptedException e) {
            print(e + ": task "+ this +" interruped");
        }
    }
}


// Waits on the CountDownLatch
class WaitingTask implements Runnable {
    
    private static int counter = 0;
    private final int id = counter++;
    private final CountDownLatch latch;
    
    public WaitingTask(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public String toString() {
        return String.format("WaitingTask %1$-3d", id);
    }

    @Override
    public void run() {
        
        try {
            latch.await();
            print("Latch barrier passed for " + this);
        } catch (InterruptedException e) {
            print(this + " interrupted");
        }
        
    }

}


/** CountDownLatch 用来同步一个或者多个任务，强制它们等待由其它任务执行的一组操作完成
 * @author yzhou-citrix
 *
 */
public class CountDownLatchDemo {

    static final int SIZE = 100;
    
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        
        CountDownLatch latch = new CountDownLatch(SIZE);
        
        for(int i =0; i < 10; i++) {
            exec.execute(new WaitingTask(latch));
        }
        
        for(int i =0; i < 100; i++) {
            exec.execute(new TaskPortion(latch));
        }
        
        print("Lauched all tasks");
        
        exec.shutdown();// quit when all tasks complete
    }
}
